// 顶点着色器
const vertexShaderSource = `
    attribute vec4 aPosition;
    attribute vec2 aTexCoord;
    uniform mat4 uModelMatrix;
    varying vec2 vTexCoord;
    void main() {
        gl_Position = uModelMatrix * aPosition;
        vTexCoord = aTexCoord;
    }
`;

// 片元着色器
const fragmentShaderSource = `
    precision mediump float;
    uniform sampler2D uSampler;
    varying vec2 vTexCoord;
    void main() {
        gl_FragColor = texture2D(uSampler, vTexCoord);
    }
`;

// 创建着色器方法
function createShader(gl, type, source) {
    const shader = gl.createShader(type);
    gl.shaderSource(shader, source);
    gl.compileShader(shader);
    
    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        console.error('着色器编译失败: ' + gl.getShaderInfoLog(shader));
        gl.deleteShader(shader);
        return null;
    }
    return shader;
}

// 加载纹理
async function loadTexture(gl, url) {
    const texture = gl.createTexture();
    
    return new Promise((resolve, reject) => {
        const image = new Image();
        image.onload = () => {
            gl.bindTexture(gl.TEXTURE_2D, texture);
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);

            // 设置纹理参数以处理非2次幂纹理
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
            resolve(texture);
        };
        image.onerror = reject
        image.src = url;
    });
}

let dpr = window.devicePixelRatio

// 初始化WebGL
async function initWebGL() {
    const canvas = document.createElement('canvas');
    canvas.width = window.innerWidth * dpr;
    canvas.height = window.innerHeight * dpr;
    document.getElementById('app').appendChild(canvas);
    
    const gl = canvas.getContext('webgl');
    if (!gl) {
        console.error('WebGL不可用');
        return;
    }

    // 创建着色器程序
    const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
    const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
    const program = gl.createProgram();
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);
    gl.linkProgram(program);
    gl.useProgram(program);
    
    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
        console.error('程序链接失败: ' + gl.getProgramInfoLog(program));
        return;
    }
    
    // 立方体顶点（位置和纹理坐标）
    const vertices = new Float32Array([
        // 前面
        -0.5, -0.5,  0.5,   0.0, 0.0,  // 左下
         0.5, -0.5,  0.5,   1.0, 0.0,  // 右下
         0.5,  0.5,  0.5,   1.0, 1.0,  // 右上
        -0.5,  0.5,  0.5,   0.0, 1.0,  // 左上
        // 后面
        -0.5, -0.5, -0.5,   1.0, 0.0,
         0.5, -0.5, -0.5,   0.0, 0.0,
         0.5,  0.5, -0.5,   0.0, 1.0,
        -0.5,  0.5, -0.5,   1.0, 1.0,
        // 上面
        -0.5,  0.5, -0.5,   0.0, 0.0,
         0.5,  0.5, -0.5,   1.0, 0.0,
         0.5,  0.5,  0.5,   1.0, 1.0,
        -0.5,  0.5,  0.5,   0.0, 1.0,
        // 下面
        -0.5, -0.5, -0.5,   0.0, 0.0,
         0.5, -0.5, -0.5,   1.0, 0.0,
         0.5, -0.5,  0.5,   1.0, 1.0,
        -0.5, -0.5,  0.5,   0.0, 1.0,
        // 右面
         0.5, -0.5, -0.5,   0.0, 0.0,
         0.5,  0.5, -0.5,   1.0, 0.0,
         0.5,  0.5,  0.5,   1.0, 1.0,
         0.5, -0.5,  0.5,   0.0, 1.0,
        // 左面
        -0.5, -0.5, -0.5,   1.0, 0.0,
        -0.5,  0.5, -0.5,   0.0, 0.0,
        -0.5,  0.5,  0.5,   0.0, 1.0,
        -0.5, -0.5,  0.5,   1.0, 1.0,
    ]);
    
    // 顶点索引
    const indices = new Uint8Array([
        0,  1,  2,    0,  2,  3,  // 前
        4,  5,  6,    4,  6,  7,  // 后
        8,  9,  10,   8,  10, 11, // 上
        12, 13, 14,   12, 14, 15, // 下
        16, 17, 18,   16, 18, 19, // 右
        20, 21, 22,   20, 22, 23  // 左
    ]);
    
    // 创建缓冲区
    const vertexBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
    
    const indexBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
    
    const aPosition = gl.getAttribLocation(program, 'aPosition');
    const aTexCoord = gl.getAttribLocation(program, 'aTexCoord');
    const uModelMatrix = gl.getUniformLocation(program, 'uModelMatrix');
    
    // 设置顶点属性指针
    gl.vertexAttribPointer(aPosition, 3, gl.FLOAT, false, 20, 0);
    gl.vertexAttribPointer(aTexCoord, 2, gl.FLOAT, false, 20, 12);
    gl.enableVertexAttribArray(aPosition);
    gl.enableVertexAttribArray(aTexCoord);

    gl.activeTexture(gl.TEXTURE0);
    // 加载纹理
    await loadTexture(gl, '/xa.png');
    gl.uniform1i(gl.getUniformLocation(program, 'uSampler'), 0);

    // 启用深度测试
    gl.enable(gl.DEPTH_TEST);
    
    let angle = 0;
    function render() {
        // 清除画布
        let viewportSize = Math.min(canvas.width, canvas.height) / 2;
        let x = (canvas.width - viewportSize) / 2;
        let y = (canvas.height - viewportSize) / 2;
        gl.viewport(x, y, viewportSize, viewportSize);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
        gl.clearColor(0.0, 0.0, 0.0, 1.0);
        
        // 计算模型矩阵
        // 绕Y轴旋转矩阵
        const rotationY = new Float32Array([
            Math.cos(angle), 0, Math.sin(angle), 0,
            0, 1, 0, 0,
            -Math.sin(angle), 0, Math.cos(angle), 0,
            0, 0, 0, 1
        ]);
        
        // 绕X轴旋转矩阵
        const rotationX = new Float32Array([
            1, 0, 0, 0,
            0, Math.cos(angle), -Math.sin(angle), 0,
            0, Math.sin(angle), Math.cos(angle), 0,
            0, 0, 0, 1
        ]);
        
        // 将两个旋转矩阵相乘
        const modelMatrix = new Float32Array(16);
        for (let i = 0; i < 4; i++) {
            for (let j = 0; j < 4; j++) {
                let sum = 0;
                for (let k = 0; k < 4; k++) {
                    sum += rotationX[i * 4 + k] * rotationY[k * 4 + j];
                }
                modelMatrix[i * 4 + j] = sum;
            }
        }
        
        gl.useProgram(program);
        gl.uniformMatrix4fv(uModelMatrix, false, modelMatrix);
        
        // 绘制立方体
        gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_BYTE, 0);
        
        angle += 0.01;
        requestAnimationFrame(render);
    }
    
    render();
}

// 页面加载完成后初始化WebGL
window.onload = initWebGL;